<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Request;

class Order extends Backend
{
    public $navTitle = 'order';

    public function __construct()
    {
        parent::__construct();

        $this->OrderModel = model('Order.Order');
        $this->UserModel = model('User.User');
        $this->OrderProModel = model('Order.OrderProduct');
    }

    public function index()
    {
        $orderList = $this->OrderModel->with(['user', 'express'])->paginate(10);

        $status = [
            '1' => '已支付，未发货',
            '2' => '已发货，未收货',
            '3' => '已收货，待评价',
            '4' => '已评价',
            '5' => '未支付',
            '-1' => '已退货',
            '-2' => '退货中',
            '-3' => '拒绝退货',
        ];

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'orderList' => $orderList,
            'status' => $status,
        ]);
    }

    // TODO 修改页面渲染
    public function edit()
    {
        $orderid = $this->request->param('id');

        $order = $this->OrderModel->with(['user', 'express'])->find($orderid);

        $express = model('Express.Express')->select();

        if (!$order) $this->error('订单不存在');

        $status = [
            '1' => '已支付，未发货',
            '2' => '已发货，未收货',
            '3' => '已收货，待评价',
            '4' => '已评价',
            '5' => '未支付',
            '-1' => '已退货',
            '-2' => '退货中',
            '-3' => '拒绝退货',
        ];

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'order' => $order,
            'status' => $status,
            'express' => $express,
        ]);
    }

    // TODO 回收站
    public function appman()
    {
        $orderList = $this->OrderModel->onlyTrashed()->paginate(10);

        if ($this->request->isAjax()) {
            $formData = $this->request->param();

            $action = $this->request->param('action');

            if ($action == 'return') {
                // TODO 软删除时将其子模型下的订单商品也一起移入回收站
                // TODO 开启事务 pre_order pre_order_product
                $this->OrderModel->startTrans();
                $this->OrderProModel->startTrans();

                $orderid = $this->request->param('orderid', '');

                $order = $this->OrderModel->onlyTrashed()->find($orderid);

                if (!$order) $this->error('订单不存在');

                // $order->restore() === FALSE ? $this->error('订单还原失败') : $this->success('订单还原成功');

                $OrderRes = $order->restore();

                if ($OrderRes === false) $this->error('订单还原失败');

                $OrderProducts = $this->OrderProModel->onlyTrashed()->where('orderid', $orderid)->select();

                $idArr = [];

                foreach ($OrderProducts as $item) {
                    $idArr[] = $item['id'];
                }

                $OrderProductRes = $this->OrderProModel->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                if ($OrderProductRes === FALSE) {
                    $this->OrderModel->rollback();
                    $this->error('订单商品还原失败，错误提示：' . $this->OrderProModel->getError());
                }

                if ($OrderProductRes === FALSE || $OrderRes === FALSE) {
                    $this->OrderModel->rollback();
                    $this->OrderProModel->rollback();
                    $this->error('订单还原失败');
                } else {
                    $this->OrderModel->commit();
                    $this->OrderProModel->commit();
                    $this->success('订单还原成功', url('admin/order/appman'));
                }
            }

            if ($action == 'returns') {
                // TODO 转存idArr
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = $this->OrderModel->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                $result === FALSE ? $this->error('订单还原失败,' . $this->OrderModel->getError()) : $this->success('订单还原成功');
            }

            // ? 还差删除子模型OrderProduct的数据
            if ($action == 'del') {
                $orderid = $this->request->param('orderid', '');

                $order = $this->OrderModel->onlyTrashed()->find($orderid);

                if (!$order) $this->error('订单不存在');

                $result = $this->OrderModel->destroy($orderid, true);

                $result === FALSE ? $this->error('订单删除失败,' . $this->OrderModel->getError()) : $this->success('订单删除成功');
            }

            // ? 还差删除子模型OrderProduct的数据
            if ($action == 'dels') {
                // TODO 接收所有数据
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = $this->OrderModel->destroy($idArr, true);

                $result === FALSE ? $this->error('订单删除失败' . $this->OrderModel->getError()) : $this->success('订单删除成功');
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'orderList' => $orderList
        ]);
    }

    // TODO 软删除
    public function delete()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');

            if ($action == 'del') {
                $orderid = $this->request->param('orderid', '');

                $order = $this->OrderModel->find($orderid);

                if (!$order) $this->error('订单不存在');

                $OrderRes = $this->OrderModel->destroy($orderid);

                if ($OrderRes === FALSE) {
                    $this->error('订单移入回收站失败，错误提示：' . $this->OrderModel->getError());
                } else {
                    $this->success('订单移入回收站成功');
                }
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                $result = $this->OrderModel->destroy($idArr);

                $result === FALSE ? $this->error('订单移入回收站失败') : $this->success('订单移入回收站成功');
            }
        }
    }

    // TODO 查询
    public function search()
    {
        $search_field = $this->request->param('search_field');

        $keyword = $this->request->param('keyword');

        $where = [];

        if ($search_field == 'nickname') $where['user.nickname'] = ['like', "%{$keyword}%"];
        if ($search_field == 'code') $where['code'] = $keyword;
        if ($search_field == 'status') $where['code'] = $keyword;
        if ($search_field == 'expcode') $where['expcode'] = $keyword;
        if ($search_field == 'expid') $where['express.name'] = ['like', "%{$keyword}%"];

        $orderList = $this->OrderModel->with(['user', 'express'])->where($where)->paginate(10);

        return $this->fetch('index', [
            'navTitle' => $this->navTitle,
            'orderList' => $orderList
        ]);
    }

    // TODO 模态框ajax查询
    public function change_status()
    {
        $formData = $this->request->param();

        // halt($formData);

        $order = $this->OrderModel->with(['user'])->find($formData['id']);

        if (!$order) $this->error('订单不存在，请重新选择');

        $data = [
            'id' => $formData['id'],
            'status' => $formData['status']
        ];

        $result = $this->OrderModel->isUpdate()->save($data);

        if ($result === FALSE) {
            $this->error('订单状态修改失败');
        } else {
            $newOrder = $this->OrderModel->with(['user'])->find($formData['id']);

            $this->success('订单状态修改成功', '', $newOrder);
        }
        // return json_encode($data);
    }

    // TODO 更新数据
    public function update()
    {
        $formData = $this->request->param();
        // halt($formData);

        $order = $this->OrderModel->find($formData['id']);

        if (!$order) $this->error('订单不存在');

        $data = [
            'id' => $formData['id'],
            'content' => $formData['content'],
            'status' => $formData['status'],
        ];

        if ($order['expid'] != $formData['expid']) {
            // TODO 生成配送单号
            $short = model('Express.Express')->where('id', $formData['expid'])->value('short');

            $expcode = build_code($short);

            $data['expid'] = $formData['expid'];

            $data['expcode'] = $expcode;
        }

        $result = $this->OrderModel->isUpdate(true)->save($data);

        $result === FALSE ? $this->error('更新失败,' . $this->OrderModel->getError()) : $this->success('更新成功', url('/admin/order/index'));
    }
}
